import * as userApi from '@/api/user'
import * as feishuApi from '@/api/feishu'
import * as auditApi from '@/api/audit'
import { defineStore } from 'pinia'
import { useAuthStore } from '@/store'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    unauditedCount: 0,
  }),
  getters: {
    userId() {
      return this.userInfo?.userId
    },
    deptId() {
      return this.userInfo?.deptId
    },
    roleName() {
      return this.userInfo?.roleName
    },
    username() {
      return this.userInfo?.name
    },
    nickName() {
      return this.userInfo?.nickName
    },
    avatar() {
      return this.userInfo?.avatar
    },
    currentRole() {
      return this.userInfo?.currentRole || {}
    },
    roles() {
      return this.userInfo?.roles || []
    },
    isHigh() {
      // 为高管或者角色为管理员就拥有高阶权限
      return this.userInfo?.isSeniorExecutive || this.userInfo?.roleCode === 'admin'
    },
  },
  actions: {
    setUser(user) {
      this.userInfo = user
    },
    resetUser() {
      this.$reset()
    },
    setToken(val) {
      this.token = val
    },
    login(data) {
      const { setToken } = useAuthStore()
      return userApi.login(data).then((res) => {
        setToken({ accessToken: res.authorization })
      })
    },
    feishuLogin(data) {
      const { setToken } = useAuthStore()
      return feishuApi.autoLogin(data).then((res) => {
        setToken({ accessToken: res.authorization })
      })
    },
    async getUnauditedCount() {
      const { data } = await auditApi.unauditedCount()
      this.unauditedCount = data
    },
  },
})
